package com.ruoyi.web.controller.epidemic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.epidemic.domain.EpidemicControlDept;
import com.ruoyi.epidemic.domain.YqInfoCollect;
import com.ruoyi.epidemic.service.IEpidemicControlDeptService;
import com.ruoyi.epidemic.service.IYqInfoCollectService;
import com.ruoyi.epidemic.service.IsmsService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 疫情防控信息收集 外部收集

 */
@Controller
@RequestMapping("/wb/epidemic/collect")
public class YqInfoCollectControllerWB extends BaseController {
    private static final DateTimeFormatter FORMAT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
    private String prefix = "epidemic/collect";

    @Autowired
    private IsmsService smsService;

    @Autowired
    private IYqInfoCollectService yqInfoCollectService;
    @Autowired
    private IEpidemicControlDeptService epidemicControlDeptService;
    /**
     * 委外人员扫码进入页面
     */
    @GetMapping("/add/{deptId}")
    public String add(@PathVariable(value = "deptId")String deptId, ModelMap map) {
    	//从url获取部门   并传递到页面，提交时，保存到后台
        //填写类型（00企业微信 01扫码 02文件导入）
        map.put("collectType", "01");
        //填写人员类型（00内部用户 01外部用户）
        map.put("userType", "01");
        //设置部门id
        map.put("deptId", deptId);
        if(!deptId.isEmpty()) {
        	EpidemicControlDept dept = epidemicControlDeptService.selectDeptById(Long.valueOf(deptId));
        	if(dept!=null) {
        		map.put("deptName", dept.getDeptName());
        	}else {
        		map.put("msg", "填报部门不存在");
        		return "/error/deptError";
        	}
        	
        }else {
        	map.put("msg", "填报部门不存在");
        	return "/error/deptError";
        }
        
        return prefix + "/addwb";
    }

    /**
     * 委外人员信息收集
     */
    @Log(title = "疫情防控委外人员信息收集", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YqInfoCollect yqInfoCollect) {
        //校验该用户手机是否已经填报
        if (StrUtil.isNotEmpty(yqInfoCollect.getPhonenumber())) {
            yqInfoCollect.setUserId(yqInfoCollect.getPhonenumber());
            String belongDate= FORMAT_DATE.format(LocalDateTime.now());
            //根据手机号查询当前用户当天是否已经提交记录（审核状态为：未审核、通过的不能再次添加；状态为：审核未通过的可以添加）
            List<YqInfoCollect> yqInfoCollectList = yqInfoCollectService.selectYqInfoCollectByPhoneNumber(yqInfoCollect.getPhonenumber(),belongDate);
            if (ObjectUtil.isNotNull(yqInfoCollectList) &&  CollUtil.isNotEmpty(yqInfoCollectList)) {
                //返回成功，获取当前id，直接跳转到编辑页面
                return AjaxResult.success("2");
            } else {
                int num = yqInfoCollectService.insertYqInfo(yqInfoCollect);
                if (num > 0) {
                    //根据部门id查询对应的管理者并告知其进行审核提醒
                    Long deptId = yqInfoCollect.getDeptId();
                    if (ObjectUtil.isNotNull(deptId)) {
                        String userId = yqInfoCollectService.selectManagerByDeptId(deptId);
                        if (StrUtil.isNotEmpty(userId)) {
                            try {
                                smsService.send(userId, "", "", yqInfoCollect.getUserName()+"提交了疫情防控收集表，请尽快审核！");
                                logger.info("填报成功，短信提醒完成");
                            } catch (WxErrorException e) {
                                logger.info("填报成功，短信提醒失败");
                            }
                        }
                    }
                    //返回成功，获取当前id，跳转到编辑页面
                    return AjaxResult.success("1");
                }
            }
        }
        return AjaxResult.error();
    }

    /**
     * 保存成功页面
     */
    @GetMapping("/success")
    public String success(HttpServletRequest request, ModelMap map)
    {
        return "error/success";
    }
}
